<?php
namespace User\Controller;

use User\Form\RoleForm;

use Zend\Mvc\Controller\AbstractActionController;


class RoleController extends AbstractActionController
{
	protected $roleTable;
	
	public function getRoleTable()
	{
		if(!$this->roleTable)
		{
			$this->roleTable = $this->getServiceLocator()->get('User\Model\RoleTable');	
		}
		return $this->roleTable;
	}
	
	public function indexAction()
	{
		$roleArray = $this->getRoleTable()->fetchAll();
		
		return array('roleArray' => $roleArray);
	}
	
	public function addAction()
	{
		$form = new \User\Form\RoleForm();
		
		if($this->getRequest()->isPost())
		{
			$form->setData($this->params()->fromPost());
			
			if($form->isValid())
			{
				$this->getRoleTable()->save($form->getData());
				$this->redirect()->toRoute('user/process', array('controller' => 'role', 'action' => 'index'));
			}
		}

		return array('form' => $form);
	}
	
	public function detailAction()
	{
	
	}
	
	public function updateAction()
	{
		if($this->request->isPost())
		{
			$this->getRoleTable()->save($this->params()->fromPost());
			$this->redirect()->toRoute('user/process', array('controller' => 'role', 'action' => 'index'));
		}
		
		$id = $this->params()->fromQuery('id');
		$resultSet = $this->getRoleTable()->getById(intval($id));
		
		$row = $resultSet->current();
		
		$form = new RoleForm();
		$form->populateValues($row);
		
		return array('form' => $form);
	}
	
	public function deleteAction()
	{
		$id = (int)$this->params()->fromQuery('id');
		$this->getRoleTable()->delete($id);
		$this->redirect()->toRoute('user/process', array('controller' => 'role', 'action' => 'index'));
	}
}
